import { http } from "@/utils"
export const getChannels = () => {
  return async (dispatch) => {
    const res = await http.get("/channels")
    const { channels } = res.data.data
    dispatch({ type: "article/getChannels", payload: channels })
  }
}
export const getArticles = (params) => {
  return async (dispatch) => {
    const res = await http.get("/mp/articles", {
      params
    })
    const { page, per_page: pageSize, results: list, total_count: count } = res.data.data
    dispatch({
      type: "article/getArticles",
      payload: {
        // 将数据格式化成 Table 需要的格式
        list: list.map((item) => {
          return {
            ...item,
            cover: item.cover.images[0]
          }
        }),
        count,
        page,
        pageSize
      }
    })
  }
}
export const deleteArticle = (id, params) => {
  return async (dispatch) => {
    await http.delete(`/mp/articles/${id}`)
    // 继续分发异步 action，获取最新的文章列表数据
    dispatch(getArticles(params))
  }
}
export const updateArticle = (data, draft, isEdit) => {
  return async () => {
    if (isEdit) {
      // 编辑
      await http.put(`/mp/articles/${data.id}?draft=${draft ? "false" : "true"}`, data)
    } else {
      // 发布
      await http.post(`/mp/articles?draft=${draft ? "false" : "true"}`, data)
    }
  }
}

export const getArticleById = (articleId) => {
  return async (dispatch) => {
    const res = await http.get(`/mp/articles/${articleId}`)

    const {
      id,
      title,
      channel_id,
      content,
      cover: { type, images }
    } = res.data.data

    const article = {
      id,
      title,
      channel_id,
      content,
      type,
      images
    }

    dispatch({
      type: "article/getArticleById",
      payload: article
    })

    // 注意：此处需要将 文章详情数据 返回，这样，在页面中才能在请求后拿到该数据
    return article
  }
}
